"use client";

import {
  PageContainer,
  ProTable,
  ProColumns,
} from "@ant-design/pro-components";
import { Button, Tag, Space } from "antd";
import { ReloadOutlined, DownloadOutlined } from "@ant-design/icons";
import { useRef } from "react";
import { useRouter } from "next/navigation";
import type { ActionType } from "@ant-design/pro-components";
import { UserInfo, UserSearchParams, UserRole, UserStatus } from "@/types/user";
import { useOverlayManager } from "@/hooks/useOverlayManager";
import RechargeModal from "./components/RechargeModal";
import { useMessage } from "../../hooks/useMessage";

// 角色选项
const ROLE_OPTIONS = [
  { label: "超级管理员", value: UserRole.SUPER_ADMIN },
  { label: "仪器管理员", value: UserRole.INSTRUMENT_MANAGER },
  { label: "仪器操作员", value: UserRole.INSTRUMENT_OPERATOR },
  { label: "财务", value: UserRole.FINANCE },
  { label: "1级用户", value: UserRole.LEVEL_1_USER },
  { label: "2级用户", value: UserRole.LEVEL_2_USER },
  { label: "3级用户", value: UserRole.LEVEL_3_USER },
];

// 状态选项
const STATUS_OPTIONS = [
  { label: "正常", value: UserStatus.NORMAL },
  { label: "禁用", value: UserStatus.DISABLED },
];

const UsersPage: React.FC = () => {
  const router = useRouter();
  const actionRef = useRef<ActionType>(null);
  const { openOverlay } = useOverlayManager();
  const message = useMessage();

  // 模拟数据
  const mockData: UserInfo[] = [
    {
      id: "1",
      phone: "18812341234",
      realName: "李老师",
      teamName: "团队1, 团队2",
      isVerified: false,
      balance: 5000.0,
      role: UserRole.SUPER_ADMIN,
      status: UserStatus.NORMAL,
      remark: "",
    },
    {
      id: "2",
      phone: "",
      realName: "",
      teamName: "",
      isVerified: true,
      balance: 0,
      role: UserRole.INSTRUMENT_MANAGER,
      status: UserStatus.NORMAL,
      remark: "",
    },
    {
      id: "3",
      phone: "",
      realName: "",
      teamName: "",
      isVerified: false,
      balance: 0,
      role: UserRole.INSTRUMENT_OPERATOR,
      status: UserStatus.NORMAL,
      remark: "",
    },
  ];

  // 查看用户
  const handleView = (record: UserInfo) => {
    router.push(`/users/${record.id}?tab=profile`);
  };

  // 编辑用户
  const handleEdit = (record: UserInfo) => {
    router.push(`/users/${record.id}?tab=settings`);
  };

  // 查看账单
  const handleViewBill = (record: UserInfo) => {
    router.push(`/users/${record.id}?tab=bill`);
  };

  // 充值
  const handleRecharge = async (record: UserInfo) => {
    try {
      const amount = await openOverlay({
        name: "recharge-modal",
        Overlay: RechargeModal,
        props: {
          userInfo: record,
          onSubmit: async (amount: number) => {
            // TODO: 调用API进行充值
            console.log("充值:", { userId: record.id, amount });
            message.success("充值成功");
            actionRef.current?.reload();
          },
          onClose: () => {
            actionRef.current?.reload();
          },
        },
        openProp: "open",
      });

      if (amount) {
        // TODO: 调用API进行充值
        console.log("充值:", { userId: record.id, amount });
        message.success("充值成功");
        actionRef.current?.reload();
      }
    } catch (error) {
      console.error("充值失败:", error);
      message.error("充值失败");
    }
  };

  // 切换用户状态
  const handleToggleStatus = (record: UserInfo) => {
    console.log("切换用户状态:", record);
    message.success(
      `${record.status === UserStatus.NORMAL ? "禁用" : "启用"}成功`
    );
    actionRef.current?.reload();
  };

  // 表格列定义
  const columns: ProColumns<UserInfo>[] = [
    {
      title: "序号",
      dataIndex: "index",
      valueType: "index",
      width: 48,
      search: false,
    },
    {
      title: "手机号",
      dataIndex: "phone",
      width: 150,
      search: true,
    },
    {
      title: "团队",
      dataIndex: "teamName",
      width: 200,
      search: true,
    },
    {
      title: "实名认证",
      dataIndex: "isVerified",
      width: 100,
      search: false,
      render: (_, record) => (
        <Tag color={record.isVerified ? "success" : "warning"}>
          {record.isVerified ? "已认证" : "未认证"}
        </Tag>
      ),
    },
    {
      title: "个人账户余额",
      dataIndex: "balance",
      width: 120,
      search: false,
      render: (val) => `¥${val}`,
    },
    {
      title: "角色",
      dataIndex: "role",
      width: 120,
      valueType: "select",
      valueEnum: ROLE_OPTIONS.reduce((acc, item) => {
        acc[item.value] = { text: item.label };
        return acc;
      }, {} as Record<string, { text: string }>),
      search: true,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 100,
      valueType: "select",
      valueEnum: STATUS_OPTIONS.reduce((acc, item) => {
        acc[item.value] = { text: item.label };
        return acc;
      }, {} as Record<string, { text: string }>),
      render: (_, record) => (
        <Tag color={record.status === UserStatus.NORMAL ? "success" : "error"}>
          {record.status === UserStatus.NORMAL ? "正常" : "禁用"}
        </Tag>
      ),
      search: true,
    },
    {
      title: "备注",
      dataIndex: "remark",
      width: 200,
      search: false,
      ellipsis: true,
    },
    {
      title: "操作",
      valueType: "option",
      width: 280,
      fixed: "right",
      search: false,
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" onClick={() => handleView(record)}>
            查看
          </Button>
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => handleViewBill(record)}
          >
            账单
          </Button>
          <Button
            type="link"
            size="small"
            onClick={() => handleRecharge(record)}
          >
            充值
          </Button>
          <Button
            type="link"
            size="small"
            danger={record.status === UserStatus.NORMAL}
            onClick={() => handleToggleStatus(record)}
          >
            {record.status === UserStatus.NORMAL ? "禁用" : "启用"}
          </Button>
        </Space>
      ),
    },
  ];

  // 数据请求
  const request = async (
    params: UserSearchParams & { current?: number; pageSize?: number }
  ) => {
    console.log("请求参数:", params);

    let filteredData = [...mockData];

    // 搜索过滤
    if (params.keyword) {
      filteredData = filteredData.filter(
        (item) =>
          (item.phone || "").includes(params.keyword!) ||
          (item.realName || "").includes(params.keyword!)
      );
    }

    if (params.role) {
      filteredData = filteredData.filter((item) => item.role === params.role);
    }

    if (params.status) {
      filteredData = filteredData.filter(
        (item) => item.status === params.status
      );
    }

    if (params.teamName) {
      filteredData = filteredData.filter((item) =>
        (item.teamName || "").includes(params.teamName!)
      );
    }

    return {
      data: filteredData,
      success: true,
      total: filteredData.length,
    };
  };

  return (
    <PageContainer>
      <ProTable<UserInfo>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: "auto",
          defaultCollapsed: false,
          span: 6,
        }}
        form={{
          syncToUrl: true,
        }}
        toolbar={{
          search: {
            onSearch: (value) => {
              console.log("搜索:", value);
            },
            placeholder: "请输入手机号/姓名",
          },
          actions: [
            <Button key="reload" icon={<ReloadOutlined />}>
              重置
            </Button>,
            <Button key="export" icon={<DownloadOutlined />}>
              导出列表
            </Button>,
          ],
        }}
        request={request}
        columns={columns}
        pagination={{
          defaultPageSize: 50,
          showSizeChanger: true,
        }}
        scroll={{ x: 1500 }}
        options={{
          density: true,
          fullScreen: true,
          setting: true,
        }}
      />
    </PageContainer>
  );
};

export default UsersPage;
